<template>
  <app-dialog-form
    :title="props.cateItem ? '编辑分类' : '添加分类'"
    :confirm="handleSubmit"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item
        label="父级"
        prop="pid"
      >
        <el-select
          v-model="formData.pid"
          placeholder="请选择父级"
        >
          <el-option
            label="顶级菜单"
            :value="0"
          />
          <el-option
            v-for="item in topCategories"
            :key="item.id"
            :label="item.cate_name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="分类名称"
        prop="cate_name"
      >
        <el-input
          v-model="formData.cate_name"
          placeholder="请输入分类名称"
        />
      </el-form-item>
      <el-form-item
        label="分类图标(180*180)"
        prop="pic"
      >
        <el-upload
          class="avatar-uploader"
          action="xxx"
          :http-request="$event => { handleUpload($event, 'pic') }"
          :show-file-list="false"
        >
          <img
            v-if="formData.pic"
            :src="formData.pic"
            class="avatar"
          >
          <el-icon
            v-else
            class="avatar-uploader-icon"
          >
            <plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="PC分类大图(468*340)"
        prop="big_pic"
      >
        <el-upload
          class="avatar-uploader"
          action="xxx"
          :http-request="$event => { handleUpload($event, 'big_pic') }"
          :show-file-list="false"
        >
          <img
            v-if="formData.big_pic"
            :src="formData.big_pic"
            class="avatar"
          >
          <el-icon
            v-else
            class="avatar-uploader-icon"
          >
            <plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="排序"
        prop="sort"
      >
        <el-input v-model.number="formData.sort" />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="formData.is_show">
          <el-radio
            :label="1"
          >
            显示
          </el-radio>
          <el-radio
            :label="0"
          >
            隐藏
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </app-dialog-form>
</template>

<script lang="ts" setup>
import { Plus } from '@element-plus/icons'
import { nextTick, ref } from 'vue'
import type { PropType } from 'vue'
import type { IElForm, IFormRule } from '@/types/element-plus'
import { ElMessage } from 'element-plus'
import { saveCategory, updateCategory } from '@/api/product'
import { ProductCategory } from '@/api/types/product'
import { uploadFile } from '@/api/file'

const props = defineProps({
  cateItem: {
    type: Object as PropType<ProductCategory | null>,
    default: null
  },
  topCategories: {
    type: Array as PropType<ProductCategory[]>,
    default: () => []
  }
})

interface EmitsType {
  (e: 'update:cate-item', value: ProductCategory | null): void
  (e: 'success'): void
}

const emit = defineEmits<EmitsType>()

const form = ref<IElForm | null>(null)
const formData = ref<Record<string, any>>({
  cate_name: '',
  is_show: 1,
  pid: 0,
  sort: 0,
  pic: '',
  big_pic: ''
})

const formRules: IFormRule = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ],
  pid: [
    { required: true, message: '请选择父级分类', trigger: 'change' }
  ]
}

const handleDialogOpen = async () => {
  nextTick(() => {
    if (props.cateItem) {
      formData.value = {
        cate_name: props.cateItem.cate_name,
        is_show: props.cateItem.is_show,
        pid: props.cateItem.pid,
        sort: props.cateItem.sort || 0,
        pic: props.cateItem.pic || '',
        big_pic: props.cateItem.big_pic || ''
      }
    }
  })
}

const handleDialogClosed = () => {
  emit('update:cate-item', null)
  form.value?.clearValidate() // 清除验证结果
  form.value?.resetFields() // 清除表单数据
}

const handleSubmit = async () => {
  const valid = await form.value?.validate()
  if (!valid) {
    return
  }
  props.cateItem
    ? await updateCategory(formData.value as ProductCategory, props.cateItem.id)
    : await saveCategory(formData.value as ProductCategory)
  emit('success')
  ElMessage.success('保存成功')
}

const handleUpload = async ({ file }: { file: File }, prop: keyof typeof formData.value) => {
  const data = await uploadFile({
    pid: 0,
    file
  })
  formData.value[prop] = `https://shop.fed.lagou.com${data.src}`
}

</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}

:deep(.avatar-uploader .el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
:deep(.avatar-uploader .el-upload:hover) {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 55px;
  height: 55px;
  text-align: center;
}
:deep(.avatar-uploader-icon svg) {
  margin-top: 14px; /* (178px - 28px) / 2 - 1px */
}
.avatar {
  width: 55px;
  height: 55px;
  display: block;
}
</style>
